
import axios, { Axios, AxiosRequestConfig } from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
type Diff<T extends keyof any, U extends keyof any> = ({ [P in T]: P } & { [P in U]: never } & { [x: string]: never })[T]
type Overwrite<T, U> = Pick<T, Diff<keyof T, keyof U>> & U


let loading: any

function startLoading() {
  loading = ElLoading.service({
    lock: true,
    text: '加载中……',
    target: document.querySelector('.layout-main') as HTMLElement,
    background: 'transparent'
  })
}

function endLoading() {
  loading.close()
}
let needLoadingRequestCount = 0
export function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}

const service = axios.create({
  baseURL: '/ad-upload-api',
  timeout: 60000,
  headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // const userStore = store.userStore
    if (!config.headers) {
      config.headers = {}
    }
    config.headers.Authorization = localStorage.getItem('sport-token')
    // if (userStore?.token || localStorage.getItem('sport-token')) {
    //   config.headers.Authorization = userStore.token || localStorage.getItem('sport-token')
    // }
    let configUrl = config.url as string;
    showFullScreenLoading()
    // 追加时间戳，防止GET请求缓存
    if (config.method?.toUpperCase() === 'GET') {
      config.params = { ...config.params, t: new Date().getTime() }
    }

    if (Object.values(config.headers).includes('application/x-www-form-urlencoded')) {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
// baseResponse
service.interceptors.response.use(
  response => {

    const res = response.data || []
    tryHideFullScreenLoading()
    // 响应成功
    return res
  },
  error => {
    console.log('error: ', error);
    let { msg, code, status } = error.response.data;


    if (code === "B2002") {
      store.userStore?.setToken('')
      localStorage.removeItem("sport-token");
      localStorage.removeItem("orgCode");
      ElMessage.error(msg)
      location.reload()
    }
    tryHideFullScreenLoading()
    return Promise.reject(error)
  }
)

// 导出 axios 实例
export default service
